<template>
  <div class="login-container">
    <div class="background-decoration">
      <div class="circle circle-1"></div>
      <div class="circle circle-2"></div>
      <div class="circle circle-3"></div>
    </div>

    <n-card class="login-card" hoverable>
      <div class="logo-container">
        <n-icon size="36" color="#2080f0" class="logo-icon">
          <Shield />
        </n-icon>
      </div>

      <n-gradient-text type="info" :size="24" class="title">
        博客后台管理系统
      </n-gradient-text>

      <div class="welcome-text">欢迎回来！请登录您的账号</div>

      <n-form ref="loginRef" :model="loginForm" :rules="loginRules" size="large" @keyup.enter="handleLogin">
        <n-form-item path="username">
          <n-input v-model:value="loginForm.username" placeholder="账号" clearable>
            <template #prefix>
              <n-icon :component="PersonOutline" color="#808695" />
            </template>
          </n-input>
        </n-form-item>

        <n-form-item path="password" style="margin-top: -40px;">
          <n-input v-model:value="loginForm.password" type="password" show-password-on="click" placeholder="密码">
            <template #prefix>
              <n-icon :component="LockClosedOutline" color="#808695" />
            </template>
          </n-input>
        </n-form-item>

        <n-form-item v-if="captchaEnabled" path="code" class="captcha-item">
          <n-input v-model:value="loginForm.code" placeholder="验证码" style="flex: 1">
            <template #prefix>
              <n-icon :component="ShieldCheckmarkOutline" color="#808695" />
            </template>
          </n-input>
          <n-image :src="codeUrl" @click="getCode" class="captcha-image" preview-disabled />
        </n-form-item>

        <n-space justify="space-between" align="center">
          <n-checkbox v-model:checked="loginForm.rememberMe">
            记住密码
          </n-checkbox>
          <n-button text type="primary" v-if="register" @click="$router.push('/register')">
            立即注册
          </n-button>
        </n-space>

        <n-button type="primary" size="large" :loading="loading" @click="handleLogin" block strong class="login-btn">
          {{ loading ? '登录中...' : '登 录' }}
        </n-button>
      </n-form>

      <div class="additional-options">
        <n-button text size="small" @click="handleForgotPassword">忘记密码？</n-button>
        <n-divider vertical />
        <n-button text size="small" v-if="register" @click="$router.push('/register')">创建新账号</n-button>
      </div>
    </n-card>

  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  NCard,
  NForm,
  NFormItem,
  NInput,
  NCheckbox,
  NButton,
  NSpace,
  NImage,
  NGradientText,
  NIcon,
  NDivider,
  useMessage
} from 'naive-ui'
import {
  PersonOutline,
  LockClosedOutline,
  ShieldCheckmarkOutline,
  ShieldOutline as Shield
} from '@vicons/ionicons5'
import { getCodeImg } from "@/api/login"
import Cookies from "js-cookie"
import { encrypt, decrypt } from "@/utils/jsencrypt"
import useUserStore from '@/store/modules/user'

const message = useMessage()
const userStore = useUserStore()
const route = useRoute()
const router = useRouter()

const loginForm = ref({
  username: "admin",
  password: "admin123",
  rememberMe: false,
  code: "",
  uuid: ""
})

const loginRules = {
  username: {
    required: true,
    trigger: ["blur", "input"],
    message: "请输入您的账号"
  },
  password: {
    required: true,
    trigger: ["blur", "input"],
    message: "请输入您的密码"
  },
  code: {
    required: true,
    trigger: ["blur", "input"],
    message: "请输入验证码"
  }
}

const codeUrl = ref("")
const loading = ref(false)
const captchaEnabled = ref(true)
const register = ref(false)
const redirect = ref(undefined)

watch(route, (newRoute) => {
  redirect.value = newRoute.query && newRoute.query.redirect
}, { immediate: true })

const handleLogin = () => {
  if (loading.value) return

  loading.value = true

  // 记住密码处理
  if (loginForm.value.rememberMe) {
    Cookies.set("username", loginForm.value.username, { expires: 30 })
    Cookies.set("password", encrypt(loginForm.value.password), { expires: 30 })
    Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 })
  } else {
    Cookies.remove("username")
    Cookies.remove("password")
    Cookies.remove("rememberMe")
  }

  // 登录逻辑
  userStore.login(loginForm.value)
      .then(() => {
        const query = route.query
        const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
          if (cur !== "redirect") {
            acc[cur] = query[cur]
          }
          return acc
        }, {})
        router.push({ path: redirect.value || "/", query: otherQueryParams })
        message.success('登录成功')
      })
      .catch(() => {
        message.error('登录失败，请检查账号密码')
        if (captchaEnabled.value) getCode()
      })
      .finally(() => {
        loading.value = false
      })
}

const handleForgotPassword = () => {
  message.info('密码找回功能正在开发中...')
}

const getCode = () => {
  getCodeImg().then(res => {
    captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled
    if (captchaEnabled.value) {
      codeUrl.value = "data:image/gif;base64," + res.img
      loginForm.value.uuid = res.uuid
    }
  })
}

const getCookie = () => {
  const username = Cookies.get("username")
  const password = Cookies.get("password")
  const rememberMe = Cookies.get("rememberMe")
  loginForm.value = {
    username: username === undefined ? loginForm.value.username : username,
    password: password === undefined ? loginForm.value.password : decrypt(password),
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
  }
}

onMounted(() => {
  getCode()
  getCookie()
})
</script>

<style lang="scss" scoped>
.login-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #c2e9fb 0%, #a1c4fd 100%);
  position: relative;
  overflow: hidden;
}

.background-decoration {
  position: absolute;
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 0;
}

.circle {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
}

.circle-1 {
  width: 300px;
  height: 300px;
  top: -100px;
  right: -50px;
  background: radial-gradient(circle, rgba(255, 255, 255, 0.3) 0%, transparent 70%);
  animation: float 15s ease-in-out infinite;
}

.circle-2 {
  width: 500px;
  height: 500px;
  bottom: -200px;
  left: -100px;
  background: radial-gradient(circle, rgba(255, 255, 255, 0.2) 0%, transparent 70%);
  animation: float 20s ease-in-out infinite reverse;
}

.circle-3 {
  width: 200px;
  height: 200px;
  top: 50%;
  left: 10%;
  background: radial-gradient(circle, rgba(255, 255, 255, 0.15) 0%, transparent 70%);
  animation: float 18s ease-in-out infinite;
}

@keyframes float {
  0% {
    transform: translate(0, 0) rotate(0deg);
  }

  50% {
    transform: translate(30px, 20px) rotate(180deg);
  }

  100% {
    transform: translate(0, 0) rotate(360deg);
  }
}

.login-card {
  width: 420px;
  border-radius: 16px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 1;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  padding: 30px 25px;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
  }
}

.logo-container {
  display: flex;
  justify-content: center;
  margin-bottom: 15px;
}

.logo-icon {
  padding: 10px;
  background: rgba(32, 128, 240, 0.1);
  border-radius: 50%;
}

.title {
  display: block;
  text-align: center;
  margin-bottom: 10px;
  font-weight: 600;
  letter-spacing: 1px;
}

.welcome-text {
  text-align: center;
  color: #606266;
  margin-bottom: 25px;
  font-size: 14px;
}

.captcha-item {
  display: flex;
  align-items: center;
  gap: 10px;

  .captcha-image {
    height: 40px;
    cursor: pointer;
    border-radius: 6px;
    border: 1px solid #eee;
    transition: all 0.2s;

    &:hover {
      transform: scale(1.05);
      border-color: #2080f0;
    }
  }
}

.login-btn {
  margin-top: 20px;
  height: 45px;
  font-weight: 500;
  letter-spacing: 2px;
  border-radius: 8px;
  box-shadow: 0 5px 15px rgba(32, 128, 240, 0.2);
  transition: all 0.3s;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 20px rgba(32, 128, 240, 0.3);
  }
}

.additional-options {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  font-size: 13px;
  color: #606266;
}

.footer {
  position: fixed;
  bottom: 20px;
  text-align: center;
  width: 100%;
  opacity: 0.8;
}

@media (max-width: 480px) {
  .login-card {
    width: 90%;
    padding: 20px 15px;
  }
}
</style>